<template>
  <div class="analysis-main-container">
    <div>
      <el-tabs v-model="activeName" class="analysis-tabs" @tab-click="handleClick">
        <el-tab-pane label="线索分析" name="first">
          <!-- 1 -->
          <el-form :model="form" label-width="auto" style="max-width: 100%">
            <el-row>
              <el-form-item label="渠道来源">
                <el-select v-model="form.channelName" placeholder="渠道来源">
                  <el-option v-for="(item, index) in clueContent" :key="index" :label="item.channelName"
                    :value="item.channelId" />
                </el-select>
              </el-form-item>
              <el-form-item label="线索状态">
                <el-select v-model="form.dictLabel" placeholder="线索状态">
                  <el-option v-for="(item, index) in clueStatusContent" :key="index" :label="item.dictLabel"
                    :value="item.dictValue" />
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
                  @change="handleDateChange" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search">搜索</el-button>
                <el-button :icon="Refresh">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
          <!-- 2 -->
          <div class="clue-analysis-section">
            <h4>线索分析</h4>
            <div ref="chartRef" style="width: 600px; height: 400px;"></div>
          </div>
          <!-- 3 -->
          <div>
            <el-table :data="tableData" style="width: 100%" border>
              <el-table-column prop="date" label="时间" width="150" />
              <el-table-column prop="name" label="线索增量" width="120" />
              <el-table-column prop="state" label="线索存量" />
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商机分析" name="second">
          <!-- 1 -->
          <el-row>
            <el-form-item label="创建时间">
              <el-date-picker v-model="dateRange" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
                @change="handleDateChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search">搜索</el-button>
              <el-button :icon="Refresh">重置</el-button>
            </el-form-item>
          </el-row>
          <!-- 2 -->
          <div class="business-analysis-section">
            <h4>商机分析</h4>
            <div ref="businessRef" style="width: 1670px; height: 400px;">
            </div>
          </div>
          <div>
            <el-table :data="tableDataBusiness" style="width: 100%" border>
              <el-table-column prop="date" label="时间" width="150" />
              <el-table-column prop="name" label="商机增量" width="120" />
              <el-table-column prop="state" label="商机存量" />
            </el-table>
          </div>

        </el-tab-pane>
        <el-tab-pane label="活动分析" name="third">

        </el-tab-pane>
        <el-tab-pane label="渠道分析" name="fourth">
          <!-- 1 -->
          <el-row>
            <el-form-item label="创建时间">
              <el-date-picker v-model="dateRange" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
                @change="handleDateChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search">搜索</el-button>
              <el-button :icon="Refresh">重置</el-button>
            </el-form-item>
          </el-row>
          <!-- 2 -->
          <div class="channel-analysis-section">
            <!-- <h4>渠道分析</h4> -->
            <div ref="channelRef" style="width: 100%; height: 400px;"></div>
            <h4>活动有效率分析</h4>
            <div ref="channelRef2" style="width: 100%; height: 400px;"></div>
          </div>
          <!-- 3 -->
          <div>
            <el-table :data="tableDataChannel" stripe style="width: 100%" border>
              <el-table-column prop="name" label="渠道名称" width="180" />
              <el-table-column prop="count" label="线索数量" width="180" />
              <el-table-column prop="available" label="线索有效率" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { clueList, clueStatusList, channelList } from "../../../api/analysis"
// top********************
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
// center*******************************
const form = reactive({
  channelName: '',
  dictLabel: '',
  params: {
    beginTime: '',
    endTime: ''
  },
})
// 获取日期
const dateRange = ref([]);
function handleDateChange(dateValue: any) {
  if (dateValue && dateValue.length === 2) {
    form.params.beginTime = dateValue[0];
    form.params.endTime = dateValue[1];
  }
}
const clueContent = ref()//线索分析--渠道来源
const clueStatusContent = ref([]);//线索分析--线索状态
const tableData = ref([])//线索分析
const tableDataBusiness = ref([])//商机分析
const tableDataChannel = ref([])//渠道分析
onMounted(() => {
  getList()
})
const channelChartData: any = ref([]);
const channelChartData2: any = ref([]);
const channelName: any = ref([]);
// 调用接口
const getList = (() => {
  clueList(form).then(res => {
    clueContent.value = res.data
  })
  clueStatusList(form).then(res => {
    clueStatusContent.value = res.data
  })
  channelList(query).then(res => {
    tableDataChannel.value = res.data;
    // 遍历添加数据到channelChartData
    channelChartData.value = [];
    for (const item of res.data) {
      channelChartData.value.push({
        name: item.name,
        value: item.count
      });
    }
    // 遍历添加数据到channelChartData2
    channelChartData2.value = [];
    // 遍历数据，直接 push 数值（而非对象）
    for (const item of res.data) {
      channelChartData2.value.push(item.available);
      channelName.value.push(item.name);
    }
    // 数据更新后，同时更新两个图表
    updateChannelChart();//更新渠道分析---图表1
    initChannelChart2(); //更新渠道分析---图表2
  }).catch(err => {
    console.error('接口请求失败', err);
  });
})
const query = reactive({
  pageNum: 1,
  pageSize: 10
})
// echarts**************************************************
// 引入 echarts 库
import * as echarts from 'echarts'
// 线索分析************************************************
// 获取 DOM 元素的引用（用于初始化图表）
const chartRef = ref(null)
// 存储 ECharts 实例
let chartInstance: any = null
// 初始化图表的方法
const initChart = () => {
  if (chartRef.value) {
    // 初始化 echarts 实例
    chartInstance = echarts.init(chartRef.value)

    // 配置项
    const option = {
      color: ['#FFD85C', '#37A2DA'], // 定义图例颜色

      tooltip: {
        trigger: 'axis'
      },
      // 说明
      legend: {
        data: ['增量数据', '存量数据'],
        bottom: 20,
        orient: 'vertical',      // 垂直方向排列,
        left: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '20%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      // x轴
      xAxis: {
        type: 'category',
        boundaryGap: false,
        // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      // y轴
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '增量数据',
          type: 'line',
          stack: 'Total',
        },
        {
          name: '存量数据',
          type: 'line',
          stack: 'Total',

        }
      ]
    };

    // 使用配置项渲染图表
    chartInstance.setOption(option)
  }
}
// 商机分析***************
// 获取 DOM 元素的引用（用于初始化图表）
const businessRef = ref(null)
// 存储 ECharts 实例
let businessInstance: any = null
// 初始化图表的方法
const initBusinessChart = () => {
  if (businessRef.value) {
    // 初始化 echarts 实例
    businessInstance = echarts.init(businessRef.value)

    // 配置项
    const option = {
      color: ['#FFD85C', '#37A2DA'], // 定义图例颜色

      tooltip: {
        trigger: 'axis'
      },
      // 说明
      legend: {
        data: ['增量数据', '存量数据'],
        bottom: 30,
        // orient: 'vertical',      // 垂直方向排列,
        left: "center"
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '20%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      // x轴
      xAxis: {
        type: 'category',
        boundaryGap: false,
        // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      // y轴
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '增量数据',
          type: 'line',
          stack: 'Total',
        },
        {
          name: '存量数据',
          type: 'line',
          stack: 'Total',

        }
      ]
    };

    // 使用配置项渲染图表
    businessInstance.setOption(option)
  }
}
// 渠道分析*****************************************************
// 图表1=========
// 获取 DOM 元素的引用（用于初始化图表）
const channelRef = ref(null)
// 存储 ECharts 实例
let channelInstance: any = null;
// 初始化图表（仅创建实例，不设置数据）
const initChannelChart = () => {
  if (channelRef.value && !channelInstance) {
    channelInstance = echarts.init(channelRef.value);
  }
};
// 更新图表数据（数据获取后调用）
const updateChannelChart = () => {
  if (!channelInstance) return;

  const option = {
    title: { text: '渠道总数分析', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: {
      top: '10%',
      // align: 'center',      // 居中对齐 
      // orient: 'horizontal', // 水平排列（可省略，默认值）
      // itemGap: 20,          // 项间距
      orient: 'vertical',
      left: 'left'
    },
    grid: {
      top: '10%',
      containLabel: true
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: channelChartData.value  // 使用转换后的正确数据
      }
    ]
  };

  // 重新设置图表选项（触发渲染）
  channelInstance.setOption(option);
};
// 图表2============
const channelRef2 = ref(null)
// 存储 ECharts 实例
let channelInstance2: any = null
// 初始化图表的方法
const initChannelChart2 = () => {
  if (channelRef2.value) {
    // 初始化 echarts 实例
    channelInstance2 = echarts.init(channelRef2.value)

    // 配置项

    const option = {
      color: ['#37A2DA'], // 定义图例颜色

      tooltip: {
        trigger: 'axis'
      },
      // 说明
      legend: {
        data: ['活动线索有效率'],
        bottom: 30,
        // orient: 'vertical',      // 垂直方向排列,
        left: "center"
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '20%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      // x轴
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: channelName.value
      },
      // y轴
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '活动线索有效率',
          type: 'line',
          stack: 'Total',
          data: channelChartData2.value
        }
      ]
    };

    // 使用配置项渲染图表
    channelInstance2.setOption(option)
  }
}
// 窗口大小变化时调整图表尺寸
const resizeChannelChart2 = () => {
  channelInstance2?.resize()
}
const resizeChart = () => {
  chartInstance?.resize()
}
const resizeBusinessChart = () => {
  businessInstance?.resize()
}
const resizeChannelChart = () => {
  channelInstance?.resize()
}
// 组件挂载后执行初始化
onMounted(() => {
  initBusinessChart()
  // 监听窗口大小变化事件以支持响应式
  window.addEventListener('resize', resizeBusinessChart)
  initChart()
  // 监听窗口大小变化事件以支持响应式
  window.addEventListener('resize', resizeChart)
  initChannelChart()
  // 监听窗口大小变化事件以支持响应式
  window.addEventListener('resize', resizeChannelChart)
  initChannelChart2()
  // 监听窗口大小变化事件以支持响应式
  window.addEventListener('resize', resizeChannelChart2)
})
// 组件卸载前清理资源，防止内存泄漏
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeBusinessChart)
  businessInstance?.dispose() // 销毁 echarts 实例
  window.removeEventListener('resize', resizeChart)
  chartInstance?.dispose() // 销毁 echarts 实例
  window.removeEventListener('resize', resizeChannelChart)
  channelInstance?.dispose() // 销毁 echarts 实例
  window.removeEventListener('resize', resizeChannelChart2)
  channelInstance2?.dispose() // 销毁 echarts 实例
})
</script>

<style>
h4 {
  font-weight: 600;
}

.analysis-main-container {
  padding: 20px;
}

.analysis-tabs {
  /* 可根据需要添加样式 */
}

.clue-analysis-section {
  height: 400px;
  width: 100%;
}

.business-analysis-section {
  height: 400px;
  width: 1670px;
  text-align: center;
}

.channel-analysis-section {
  /* height: 800px; */
  width: 100%;
  text-align: center;
}
</style>